const express = require('express')
const path = require('path')

const app = express()

app.use(express.urlencoded())
app.use(express.json())

// 学生信息接口
app.get('/user', (req, res) => {
  const { userId } = req.query

  // 请求失败
  if (userId !== '001') {
    return res.send({ code: 10001, msg: "查询失败", data: null })
  }

  // 请求成功
  res.send({
    code: 10000,
    msg: "查询成功",
    data:
    {
      name: '程龙',
      age: '20',
      sex: '女'
    }
  })
})

app.get('/userInfo/:userId', (req, res) => {
  const { userId } = req.params

  // 请求失败
  if (userId !== '001') {
    return res.send({ code: 10001, msg: "查询失败", data: null })
  }

  // 请求成功
  res.send({
    code: 10000,
    msg: "查询成功",
    data:
    {
      name: '程龙',
      age: '20',
      sex: '女'
    }
  })
})

app.post('/adduser', (req, res) => {
  const { name, age, sex } = req.body

  if (!name || !age || !sex) {
    return res.send({
      code: 10001,
      msg: '查询失败',
      data: null
    })
  }

  res.send({
    code: 10000,
    msg: '查询成功',
    data: null
  })
})

// 静态资源部署接口
app.get('/1', (req, res) => {
  const filePath = path.resolve(__dirname, './1.基础的get请求.html')
  res.sendFile(filePath)
})

app.get('/2', (req, res) => {
  const filePath = path.resolve(__dirname, './3.get请求.html')
  res.sendFile(filePath)
})

app.get('/3', (req, res) => {
  const filePath = path.resolve(__dirname, './4.get请求-path传参.html')
  res.sendFile(filePath)
})

app.get('/4', (req, res) => {
  const filePath = path.resolve(__dirname, './5.post请求.html')
  res.sendFile(filePath)
})

app.listen(8080, () => {
  console.log('服务器启动成功')
})